package com.mohan.system.manage.utils;

import cn.hutool.extra.spring.SpringUtil;
import com.mohan.system.manage.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.Authenticator;
import org.apache.shiro.authc.LogoutAware;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;


/**
 * @author mohan
 */
public class ShiroUtils {
    /**
     * 私有构造器
     **/
    private ShiroUtils() {}

    private static SessionDAO sessionDAO = SpringUtil.getBean(SessionDAO.class);

    /**
     * 获取当前用户Session
     *
     * @Return SysUserEntity 用户信息
     */
    public static Session getSession() {
        return SecurityUtils.getSubject().getSession();
    }

    /**
     * 用户登出
     */
    public static void logout() {
        SecurityUtils.getSubject().logout();
    }

    /**
     * 删除用户缓存信息
     * 
     * @Param username 用户名称
     * @Param isRemoveSession 是否删除Session，删除后用户需重新登录
     */
    public synchronized static void deleteCache(String username, boolean isRemoveSession) {
        // 从缓存中获取Session
        Session session = null;
        // 获取当前已登录的用户session列表
        Collection<Session> sessions = sessionDAO.getActiveSessions();
        User sysUserEntity;
        Object attribute = null;
        // 遍历Session,找到该用户名称对应的Session
        for (Session sessionInfo : sessions) {
            attribute = sessionInfo.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
            if (attribute == null) {
                continue;
            }
            sysUserEntity = (User)((SimplePrincipalCollection)attribute).getPrimaryPrincipal();
            if (sysUserEntity == null) {
                continue;
            }
            if (Objects.equals(sysUserEntity.getUsername(), username)) {
                session = sessionInfo;
                // 清除该用户以前登录时保存的session，强制退出 -> 单用户登录处理
                if (isRemoveSession) {
                    sessionDAO.delete(session);
                }
            }
        }

        if (session == null || attribute == null) {
            return;
        }
        // 删除session
        if (isRemoveSession) {
            sessionDAO.delete(session);
        }
        // 删除Cache，再访问受限接口时会重新授权
        DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager)SecurityUtils.getSecurityManager();
        Authenticator authc = securityManager.getAuthenticator();
        ((LogoutAware)authc).onLogout((SimplePrincipalCollection)attribute);
    }

    /**
     * 获取当前用户信息
     *
     * @Return SysUserEntity 用户信息
     */
    public static User getUserInfo() {
        return (User)SecurityUtils.getSubject().getPrincipal();
    }

    /**
     * 获取在线用户列表
     * 
     * @author 张涛
     * @date 2022/01/29 17:30
     * @return * @return: java.util.List<com.suse.approval.entity.User>
     */
    public static List<User> listOnlineUser() {
        List<User> users = new ArrayList<>();
        // 获取当前已登录的用户session列表
        Collection<Session> sessions = sessionDAO.getActiveSessions();
        for (Session session : sessions) {
            Object attribute = session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
            if (attribute == null) {
                continue;
            }
            User sysUserEntity = (User)((SimplePrincipalCollection)attribute).getPrimaryPrincipal();
            if (sysUserEntity == null) {
                continue;
            }
            users.add(sysUserEntity);
        }
        return users;
    }

}
